# gc();rm(list = ls());
gc()

# library(tidyverse)
results <- read.table("results/mc/res.txt")

out <- matrix(NA, nrow(results), 33)

for (j in 1:length(results$V2)){
  
  load(paste0("data/mc/", results$V2[j], "_run.Rda"))
  load(paste0("results/mc/", results$V2[j], "_run.Rda"))
  
  # true values
  out[j, 1] <- j
  out[j, 2:4] <- c(taus, dl, cor(id)[1,2])
  
  # summary
  out[j, 5:6] <- c(max(sum_nonsep$rhat, na.rm = T), max(sum_sep$rhat, na.rm = T))
  
  # sep
  out[j, 7:8] <- sum_sep$mean[1:2] # salience
  out[j, 9:10] <- sum_sep$mean[3:4] # correlation
  out[j, 11:12] <- sum_sep$mean[6:7] # r squared
  out[j, 13] <- sum_sep$mean[5] # cor dims
  out[j, 14:15] <- sum_sep$mean[8:9] # gamma
  out[j, 16:17] <- sum_sep$mean[c(10, 12)] # complexity + pred_correct
  
  # nonsep
  out[j, 18:19] <- sum_nonsep$mean[1:2] # salience
  out[j, 20:21] <- sum_nonsep$mean[3:4] # correlation
  out[j, 22:23] <- sum_nonsep$mean[6:7] # r squared
  out[j, 24] <- sum_nonsep$mean[5] # cor dims
  out[j, 25:26] <- sum_nonsep$mean[8:9] # gamma
  out[j, 27:28] <- sum_nonsep$mean[c(10, 16)] # complexity + pred_correct
  out[j, 29] <- sum_nonsep$mean[13] # nonsep
  
  if (rownames(loo_comp)[1] == "model2"){
    out[j, 30:31] <- loo_comp[,1]
    out[j, 32:33] <- loo_comp[,2]
  } else {
    out[j, 30:31] <- rev(loo_comp[,1])
    out[j, 32:33] <- rev(loo_comp[,2])
  }
  
}

nsep <- as.data.frame(out[,c(1:4, 18:30, 32)])
sep <- as.data.frame(out[,c(1:4, 7:17, 31, 33)])

names(nsep) <- c("run", "sal_t", "nsep_t", "cor_t", "sal1", "sal2", "cor1", "cor2", "rsq1", "rsq2", "cordim",
                 "gamma1", "gamma2", "compl", "pred", "nsep", "loo", "loo_se")
names(sep) <- c("run", "sal_t", "nsep_t", "cor_t", "sal1", "sal2", "cor1", "cor2", "rsq1", "rsq2", "cordim", 
                "gamma1", "gamma2", "compl", "pred", "loo", "loo_se")

nsep$model <- "nsep"
sep$model <- "sep"

both <- dplyr::bind_rows(nsep, sep)
save(both, file = "results/mc/full.Rda")
